const cwd = process.cwd()
const path = require('path')
const { merge } = require('webpack-merge')
let CONFIG = require('../config/dait.config')
const FriendlyPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const CONFIGPATH = process.env.CONFIGPATH

try {
  const _config = require(path.join(cwd, CONFIGPATH))
  CONFIG = Object.assign({}, CONFIG, _config)
} catch (error) {}

const themePath = path.join(cwd, './themes', CONFIG.theme)

if (!CONFIG.configureWebpack.entry) {
  CONFIG.configureWebpack.entry = path.join(themePath, './main.js')
}
CONFIG.configureWebpack.alias['@theme'] = themePath

global.DAIT_CONFIG = CONFIG
global.THEME_PATH = themePath

const commonConfig = require('./webpack.common')
const { configureWebpack, configureWebpack: { dev }} = CONFIG


const devWebpackConfig = merge(commonConfig, {
  mode: 'development',
  devtool: dev.devtool,
  devServer: dev.devServer,
  module: {
    rules: configureWebpack.rules.concat(dev.rules)
  },
  plugins: configureWebpack.plugins.concat()
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = devWebpackConfig.devServer.port
  
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      devWebpackConfig.devServer.port = port

      devWebpackConfig.plugins.push(
        new FriendlyPlugin({
          compilationSuccessInfo: {
            messages: [
              `Your application is running here: http://${
                devWebpackConfig.devServer.host
              }:${port}`
            ]
          }
        })
      )
      resolve(devWebpackConfig)
    }
  })
})